<template>
	<div class="page-container">
		<el-card class="page-card">
			<el-form ref="queryForm" :inline="true" :model="queryParams" label-width="100px">
				<el-form-item label="表名称：" prop="tableName">
					<el-input v-model.trim="queryParams.tableName" clearable placeholder="请输入表名称" @keyup.enter.native="handleQuery" />
				</el-form-item>
				<el-form-item label="表描述：" prop="tableComment">
					<el-input v-model.trim="queryParams.tableComment" clearable placeholder="请输入表描述" @keyup.enter.native="handleQuery" />
				</el-form-item>
				<br />
				<start-end-time ref="child" :get-time="getTime" title="创建时间："></start-end-time>
				<el-form-item>
					<div class="page-search-btn">
						<el-button type="primary" @click="handleQuery">搜索</el-button>
						<el-button @click="resetQuery">重置</el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="page-card">
			<div class="page-card-options">
				<el-button v-hasPermi="['tool:gen:code']" type="primary" @click="handleGenTable">生成 </el-button>
				<el-button v-hasPermi="['tool:gen:import']" type="primary" @click="openImportTable">导入 </el-button>
				<el-button v-hasPermi="['tool:gen:remove']" :disabled="multiple" type="primary" @click="handleDelete">删除 </el-button>
			</div>

			<el-table v-loading="loading" :data="tableList" stripe @selection-change="handleSelectionChange">
				<el-table-column align="center" type="selection" width="55"></el-table-column>
				<el-table-column align="center" label="序号" type="index" width="55" />
				<el-table-column :show-overflow-tooltip="true" align="center" label="表名称" prop="tableName" />
				<el-table-column :show-overflow-tooltip="true" align="center" label="表描述" prop="tableComment" />
				<el-table-column :show-overflow-tooltip="true" align="center" label="实体" prop="className" />
				<el-table-column align="center" label="创建时间" min-width="160" prop="createTime" />
				<el-table-column align="center" label="更新时间" min-width="160" prop="updateTime" />
				<el-table-column :width="tableAction" align="center" fixed="right" header-align="center" label="操作">
					<template slot-scope="scope">
						<div class="table-action">
							<el-dropdown @command="handleCommand($event, scope.row)">
								<el-button type="primary"> 更多<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item command="handlePreview">预览</el-dropdown-item>
									<el-dropdown-item command="handleEditTable">编辑</el-dropdown-item>
									<el-dropdown-item command="handleDelete">删除</el-dropdown-item>
									<el-dropdown-item command="handleSynchDb">同步</el-dropdown-item>
									<el-dropdown-item command="handleGenTable">生成代码</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList" />
		</el-card>
		<!-- 预览界面 -->
		<el-dialog :title="preview.title" :visible.sync="preview.open" append-to-body top="5vh" width="80%">
			<el-tabs v-model.trim="preview.activeName">
				<el-tab-pane
					v-for="(value, key) in preview.data"
					:key="key"
					:label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
					:name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
				>
					<pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
				</el-tab-pane>
			</el-tabs>
		</el-dialog>
		<import-table ref="import" @ok="handleQuery" />
	</div>
</template>

<script>
import { delTable, genCode, listTable, previewTable, synchDb } from '@/api/tool/gen';
import importTable from './importTable';
import { downLoadZip } from '@/utils/zipdownload';
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github-gist.css';
import startEndTime from '@/components/StartEndTime';
import tableMixins from '@/mixins/table';

hljs.registerLanguage('java', require('highlight.js/lib/languages/java'));
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('html', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('vue', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
hljs.registerLanguage('sql', require('highlight.js/lib/languages/sql'));

export default {
	name: 'Gen',
	components: { importTable, startEndTime },
	mixins: [tableMixins],
	data() {
		return {
			// 遮罩层
			loading: true,
			// 唯一标识符
			uniqueId: '',
			// 选中数组
			ids: [],
			// 选中表数组
			tableNames: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 表数据
			tableList: [],
			// 日期范围
			dateRange: [],
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				tableName: undefined,
				tableComment: undefined,
			},
			// 预览参数
			preview: {
				open: false,
				title: '代码预览',
				data: {},
				activeName: 'domain.java',
			},
		};
	},
	created() {
		this.getList();
	},
	activated() {
		const time = this.$route.query.t;
		if (time != null && time != this.uniqueId) {
			this.uniqueId = time;
			this.resetQuery();
		}
	},
	methods: {
		/** 查询表集合 */
		getList() {
			this.loading = true;
			listTable(this.addDateRange(this.queryParams, this.dateRange))
				.then((response) => {
					this.tableList = response.rows;
					this.total = response.total;
					this.setActionWidth();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		//获取时间
		getTime(startTime, endTime) {
			this.$set(this.dateRange, 0, startTime);
			this.$set(this.dateRange, 1, endTime);
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 生成代码操作 */
		handleGenTable(row) {
			const tableNames = row.tableName || this.tableNames;
			if (tableNames == '') {
				this.msgError('请选择要生成的数据');
				return;
			}
			if (row.genType === '1') {
				genCode(row.tableName).then((response) => {
					this.msgSuccess('成功生成到自定义路径：' + row.genPath);
				});
			} else {
				downLoadZip('/tool/gen/batchGenCode?tables=' + tableNames, 'tencreat');
			}
		},
		/** 同步数据库操作 */
		handleSynchDb(row) {
			const tableName = row.tableName;
			this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return synchDb(tableName);
				})
				.then(() => {
					this.msgSuccess('同步成功');
				});
		},
		/** 打开导入表弹窗 */
		openImportTable() {
			this.$refs.import.show();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.$refs.child.resetTime(); //清空时间
			this.dateRange = [];
			this.resetForm('queryForm');
			this.handleQuery();
		},
		/** 预览按钮 */
		handlePreview(row) {
			previewTable(row.tableId).then((response) => {
				this.preview.data = response.data;
				this.preview.open = true;
			});
		},
		/** 高亮显示 */
		highlightedCode(code, key) {
			const vmName = key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'));
			var language = vmName.substring(vmName.indexOf('.') + 1, vmName.length);
			const result = hljs.highlight(language, code || '', true);
			return result.value || '&nbsp;';
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.tableId);
			this.tableNames = selection.map((item) => item.tableName);
			this.single = selection.length != 1;
			this.multiple = !selection.length;
		},
		/** 修改按钮操作 */
		handleEditTable(row) {
			const tableId = row.tableId || this.ids[0];
			this.$router.push('/gen/edit/' + tableId);
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const tableIds = row.tableId || this.ids;
			this.$confirm('是否确认删除表编号为"' + tableIds + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delTable(tableIds);
				})
				.then(() => {
					this.getList();
					this.msgSuccess('删除成功');
				});
		},
		handleCommand(key, row) {
			this[key](row);
		},
	},
};
</script>
